import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, first, firstValueFrom } from 'rxjs';
import { INIT_PASSWORD, LOGIN_BY_VCODE, LOG_OUT, SIGN_IN, UPDATE_USERINFO, USER_INFO, WE_CHAT_LOGIN } from 'src/app/api/login';
import { slRun_t } from '../utils/utils';
import { environment } from 'src/environments/environment';
import { MessageService } from './message.service';
import { Router } from '@angular/router';
import { UserInfoData, UserInfoService } from './user-info/user-info.service';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  constructor(
    private http: HttpClient,
    private message: MessageService,
    private router: Router,
    private userInfo: UserInfoService
  ) { }

  _loginByPwd(username: string, password: string): Observable<any>{
    let formData = new FormData()
    formData.append('language', 'zh-CHS');
    formData.append('seType', 'true');
    formData.append('Tenant', environment.Tenant) //919455
    formData.append('Authenstrategy', 'UserPassword')
    formData.append('Language', 'zh-CHS')
    formData.append('username', username)
    formData.append('password', slRun_t(password))

    return this.http.post(SIGN_IN, formData)
  }
  _getUserInfo(): Observable<any>{
    return this.http.get(USER_INFO)
  }

  _loginByVCode(phone: string, vCode: string): Observable<any>{
    const formData = new FormData()
    formData.append('Tenant', environment.Tenant) // 925543 919455
    formData.append('language', 'zh-CHS');
    formData.append('seType', 'true');
    formData.append('Authenstrategy', 'verificationCode')
    formData.append('loginType', 'verificationCode')
    formData.append('phone', phone)
    formData.append('code', vCode)

    return this.http.post(LOGIN_BY_VCODE, formData)
  }

  // 粤省事登录
  _loginByAuthCode(code: string): Observable<any>{
    const data = new FormData();
    data.append('Tenant', environment.Tenant);
    data.append('Authenstrategy', 'verificationCode');
    data.append('loginType', 'authGd');
    data.append('authCode', code);
    data.append('language', 'zh-CHS');
    data.append('seType', 'true');

    return this.http.post(LOGIN_BY_VCODE, data)
  }
  

  _logout(): Observable<any>{
    return this.http.post(LOG_OUT, {})
  }

  _initPassword(data: any): Observable<any>{
    return this.http.post(INIT_PASSWORD, data)
  }

  _updateUserInfo(data: any): Observable<any>{
    return this.http.post(UPDATE_USERINFO, data)
  }

  _loginByWeChat(): Observable<any>{
    return this.http.get(WE_CHAT_LOGIN)
  }
  _loginByWeChatWait(key: string): Observable<any>{
    const formData = new FormData()
    formData.append('Tenant', environment.Tenant) // 925543 919455
    formData.append('language', 'zh-CHS');
    formData.append('seType', 'true');
    formData.append('Authenstrategy', 'verificationCode')
    formData.append('loginType', 'qrcode')
    formData.append('key', key)
    formData.append('type', 'wx')

    return this.http.post(LOGIN_BY_VCODE, formData)
  }

  //#region 第三方绑定
  // 1. 微信绑定 - 获取绑定 二维码
  _getWeChatBindCode(): Observable<any>{
    const url = '/api/gsxmcp/rg/rl/v1.0/authLoginWx/qrcode/bind';
    return this.http.get(url);
  }
  /**
   * 2. 等待确认
   * @param key 1 的返回
   * @param type (wx、alipay)
   */
  _getIsAuth(key: string, type: string): Observable<any>{
    const url = '/api/gsxmcp/rg/rl/v1.0/login/req';
    let args = {
      key,
      type
    }
    let params = new HttpParams({ fromObject: args });
    return this.http.get(url, { params })
  }
  //#endregion

  //#region 登录后
  async afterLogin(res: any, redirectUrl: string){
    if(res && (res.authentication === 'success' || res.message === 'success') ){
      this.message.success('登录成功')
      // if(type === '1'){
      //   try{
      //     await firstValueFrom(this.identityAuth(code))
      //   }catch(error: any){
      //     this.message.createErrorMessage(error)
      //   }
      // }
      this.getUserInfo(redirectUrl)
    }else if(res && res.error && res.error.message && res.error.message.indexOf('login has reached the limit')){
      this.message.error('登录次数超过最大限制,请稍后再试')
    }else if(res && res.error && res.error.message){
      this.message.error(res.error.message)
    }else{
      if(res && res.error && res.error.message.indexOf('not match')){
        this.message.error('用户名或密码不正确, 请重试')
      }else{
        this.message.error('登录失败')
      }
    }
    // this.submitLoading = false
  }

  // 获取用户信息
  getUserInfo(redirectUrl: string = '/home', params: any = {}){
    this._getUserInfo().subscribe({
      next: (res: UserInfoData) => {
        if(res){
          this.userInfo.setUserInfo(res)
          window.open(redirectUrl, '_self');
          // this.router.navigate([redirectUrl], { queryParams: params })
        }else{
          this.message.error('获取用户信息失败, 请重新登录')
          this.router.navigate(['/login'])
        }
      }, 
      error: error => {
        this.message.error('获取用户信息失败, 请重新登录')
        this.router.navigate(['/login'])
      }
    })
  }
  //#endregion

  // 省统一省份认证 功能
  identityAuth(code: string): Observable<any>{
    const url = `/api/gsxmcp/ot/si/v1.0/auth?code=${code}`;
    return this.http.get(url);
  }
}
